package com.silas.dynflightdatatransfer.manager.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.silas.dynflightdatatransfer.common.BusinessException;
import com.silas.dynflightdatatransfer.dao.FlightDynamicDataInfoMapper;
import com.silas.dynflightdatatransfer.manager.FlightDynamicDataInfoManager;
import com.silas.dynflightdatatransfer.model.entity.FlightDynamicDataInfo;
import com.silas.dynflightdatatransfer.enums.RespEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 飞行动态数据表管理层
 *
 * @author chentianyan
 */
@Component
public class FlightDynamicDataInfoManagerImpl extends ServiceImpl<FlightDynamicDataInfoMapper, FlightDynamicDataInfo>
        implements FlightDynamicDataInfoManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlightDynamicDataInfoManagerImpl.class);

    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    @Value("${spring.datasource.username}")
    private String datasourceUserName;
    @Value("${spring.datasource.password}")
    private String datasourcePwd;

    /**
     * 查询所有分表名称 <br/>
     * sql: SHOW TABLES LIKE 'tab_flight_dynamic_data_info%'
     *
     * @param logicTableName 逻辑表名
     * @return Set<String>
     */
    @Override
    public List<String> queryFlightDynamicDataInfoTables(String logicTableName) {
        List<String> tables = new ArrayList<>();

        Connection connection = null;
        try {
            // 获取数据库连接
            connection = DriverManager.getConnection(datasourceUrl, datasourceUserName, datasourcePwd);

            Statement statement = connection.createStatement();
            // 查询sql
            String sql = String.format("SHOW TABLES LIKE '%s%%';", logicTableName);
            ResultSet result = statement.executeQuery(sql);
            while (Objects.nonNull(result) && result.next()) {
                tables.add(result.getString(1));
            }
            statement.close();
            connection.close();
        } catch (SQLException e) {
            LOGGER.error("===> [飞行动态数据] 查询所有分表名称异常, error: ", e);
        } finally {
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (SQLException ignore) {
                }
            }
        }
        return tables;
    }

    /**
     * 创建新分表
     *
     * @param newTableName   新分表名
     * @param logicTableName 逻辑表名
     */
    @Override
    public void createTable(String newTableName, String logicTableName) {
        Connection connection = null;
        try {
            // 获取数据库连接
            connection = DriverManager.getConnection(datasourceUrl, datasourceUserName, datasourcePwd);
            connection.setAutoCommit(false);

            Statement statement = connection.createStatement();
            // 执行sql
            String sql = String.format("CREATE TABLE IF NOT EXISTS `%s` LIKE `%s`;", newTableName, logicTableName);
            boolean result = statement.execute(sql);
            LOGGER.info("===> [飞行动态数据] 创建分表: {}, 执行结果: {}", newTableName, result);
            connection.commit();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            if (Objects.nonNull(connection)) {
                try {
                    connection.rollback();
                } catch (SQLException ignore) {
                }
            }
            LOGGER.error("===> [飞行动态数据] 创建分表异常, error: ", e);
            throw new BusinessException(RespEnum.OPERATE_FAILURE);
        } finally {
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }

}
